package net.hctek.identity.util;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;

public class CookieUtils {

	
	
	public static void addCookie(String userId, String cookieName, int time) {
		Cookie cookie = getCookieByName(cookieName);
		
		if(cookie==null){
			cookie = new Cookie(cookieName,userId);
		}
		
		cookie.setValue(userId);
		
		
		cookie.setMaxAge(time);
		System.out.println("ServletActionContext.getRequest().getContextPath():"+ServletActionContext.getRequest().getContextPath());
		
		cookie.setPath(ServletActionContext.getRequest().getContextPath());
		
		ServletActionContext.getResponse().addCookie(cookie);
	}

	

	
	//����cookie���ֻ�ȡcookie��Ϣ   cookie����ڿͻ��˵������
	public static Cookie getCookieByName(String cookieName) {
		// TODO Auto-generated method stub
		Cookie[] cookies = ServletActionContext.getRequest().getCookies();
		if(cookies!=null){
			for(Cookie cookie : cookies){
				if(cookie.getName().equals(cookieName)){
					return cookie;
				}
			}
		}
		
		return null;
	}




	
	
	//����cookie����ɾ��cookie��Ϣ
	public static void removeCookie(String cookieName) {
		// TODO Auto-generated method stub
		//����cookie���ֻ�ȡcookie��Ϣ
		Cookie cookie = getCookieByName(cookieName);
		if(cookie!=null){
			//��cookie����Чʱ������
			cookie.setMaxAge(0);
			
			//����cookie��������
			cookie.setPath(ServletActionContext.getRequest().getContextPath());
			//��cookie��Ϣ��Ӧ���ͻ���
			ServletActionContext.getResponse().addCookie(cookie);
			
		}
		
	}
	
	

}
